<script setup>
import { useRoute, useRouter } from 'vue-router'
import { getproduct } from '@/apis/product'
import { createOrderAPI } from '@/apis/checkout'
import { insertCartAPI, getCartListAPI } from '@/apis/cart'
import { getComments } from '@/apis/comment'
import { useCartStore } from '@/stores/cart'
import { ref,reactive, onMounted } from 'vue'
import ImagePreview from './ImagePreview.vue'
import { ElMessage } from 'element-plus'
import GoodsDetail from './GoodsDetail.vue'
import GoodsComments from './GoodsComments.vue'

const route = useRoute()
const router = useRouter()
const product = ref({
  id: 0,
  name: '',
  subTitle: '',
  price: 0,
  param: [],
  rotation: [],
  detail: null,
  stock: 0,
})
const id = route.params.id
const num = ref(1)
const radio = ref(1)

const imgList = ref([])
const commentList = ref([])

const increse = () => {
  num.value++
}
const decrease = () => {
  if (num.value > 1) {
    num.value--
  } else {
    num.value = 1
  }
}

// 添加到购物车
const handleAddCart = async (productId, quantity) => {
  if (!localStorage.getItem('user_token')) {
    router.push('/login')
    return
  }
  await insertCartAPI({
    productId,
    quantity,
  })
    .then((res) => {
      ElMessage.success(res.message)
    })
    .catch((error) => {
      console.error('添加到购物车失败:', error)
      throw new Error('添加到购物车时发生错误')
    })
  const cartStore = useCartStore()
  // 获取最新的购物车列表
  getCartListAPI().then((res) => {
    cartStore.setCartInfo(res)
  })
}

// 处理立即购买
const handleBuy = async () => {
  if (!localStorage.getItem('user_token')) {
    router.push('/login')
    return
  }
  if (num.value > product.value.stock) {
    ElMessage.error('库存不足')
    return
  }
  const res = await createOrderAPI([
    {
      productNum: num.value,
      productId: id,
    },
  ]).catch((error) => {
    ElMessage.error('创建订单失败')
    console.error('创建订单失败:', error)
  })
  console.log(res)
  if (res.success == false) {
    ElMessage.error(res.message)
    return
  }
  // 跳转到订单确认页面
  router.push('/checkout/' + res.data)
}

async function fetchProductDetails(id) {
  try {
    // 获取商品信息
    const res = await getproduct(id).catch((error) => {
      console.error('获取商品失败:', error)
      // 这里可以根据实际情况处理错误，比如提示用户、设置默认值等
      throw new Error('获取商品信息时发生错误')
    })

    product.value = res

    // 处理旋转图片列表
    if (res.rotation) {
      imgList.value = res.rotation.split(',')
    } else {
      console.warn('rotation字段不存在或为空')
      // 可以设置默认值或做其他处理
    }

    // 尝试将param字段转换为JSON对象
    if (res.param) {
      const jsonString = res.param
      const jsonObject = JSON.parse(jsonString)
      product.value.param = jsonObject
    } else {
      console.warn('param字段不存在或为空')
      // 同样，根据需要处理这种情况
    }
  } catch (error) {
    // 这里可以统一处理所有未被捕获的异常
    console.error('处理商品数据时出现异常:', error)
    // 可能还需要通知用户或执行一些清理操作
  }
}

// 获取商品评价列表
async function fetchComments(id) {
  await getComments(id, 1, 10)
    .then((res) => {
      commentList.value = res.data.records
    })
    .catch((error) => {
      console.error('获取商品评价失败:', error)
      // 这里可以根据实际情况处理错误，比如提示用户、设置默认值等
    })
}

onMounted(async () => {
  await fetchProductDetails(id)

  await fetchComments(id)
})
const current = reactive({
  type:1
})
const component = {
  2: GoodsComments,
  1: GoodsDetail,
};
</script>

<template>
  <div class="xtx-goods-page">
    <div class="container">
      <!-- 商品信息 -->
      <div class="info-container">
        <div>
          <div class="goods-info">
            <div class="media">
              <!-- 图片预览区 -->
              <ImagePreview :imageList="imgList" />
            </div>
            <div class="spec">
              <!-- 商品信息区 -->
              <p class="g-name"> {{ product.name }} </p>
              <p class="g-desc">{{ product.subTitle }} </p>
              <p class="g-price">
                <span>{{ product.price }}</span>
              </p>
              <div class="g-service">
                <dl>
                  <dt>促销</dt>
                  <dd>12月好物放送，App领券购买直降120元</dd>
                </dl>
                <dl>
                  <dt>服务</dt>
                  <dd>
                    <span>无忧退货</span>
                    <span>快速退款</span>
                    <span>免费包邮</span>
                    <a href="javascript:;">了解详情</a>
                  </dd>
                </dl>
              </div>
              <!-- sku组件(属性组件) -->
              <div class="g-sku" v-for="(item, index) in product.param">
                <div class="label">{{ item.attr_name }}</div>
                <div style="margin-top: 20px">
                  <el-radio-group v-model="radio" v-for="(val, i) in item.attr_vals">
                    <el-radio :value="i">{{ val }}</el-radio>
                  </el-radio-group>
                </div>
              </div>

              <!-- 数据组件 -->
              <div class="xtx-numbox">
                <div class="label">数量</div>
                <div class="numbox">
                  <a href="javascript:;" @click="decrease">-</a>
                  <span>{{ num }}</span>
                  <a href="javascript:;" @click="increse">+</a>
                </div>
              </div>
              <!-- 按钮组件 -->
              <div class="xtx-btn">
                <el-button size="large" type="primary" class="btn" @click="handleAddCart(id, num)">
                  加入购物车
                </el-button>
                <el-button size="large" class="btn" @click="handleBuy">
                  立即购买
                </el-button>
              </div>
            </div>

          </div>
          <div class="goods-footer">
            <div class="goods-article">

              <div class="goods-tabs">
                <nav>
                  <a :class="{active: current.type === 1}" @click="current.type = 1">商品详情</a>
                  <a :class="{active: current.type === 2}" @click="current.type = 2">商品评价<span>({{ commentList.length }})</span></a>
                </nav>
                <keep-alive>
                  <component :is="component[current.type]" :product="product" :commentList="commentList"></component>
                </keep-alive>
                
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped lang='scss'>
$priceColor: #f00; // 假定价格颜色为红色$xtxColor: #09f; // 假定xtx颜色为一个蓝色
$background: #fff;$paddingBase: 30px;
$marginBase: 20px;

.xtx-goods-page {
  margin-top: $marginBase;

  .goods-info {
    display: flex;
    background: $background;
    min-height: 600px;

    .media {
      width: 580px;
      height: 100%;
      padding: $paddingBase 50px;
    }

    .spec {
      flex: 1;
      padding: $paddingBase$paddingBase 0 0;
    }
  }

  .goods-footer {
    display: flex;
    margin-top: $marginBase;

    .goods-article {
      width: 100%;
    }

    .goods-aside {
      width: 280px;
      min-height: 1000px;
    }

    .goods-tabs {
      background: $background;
      min-height: 600px;
      width: 100%;

      a {
        margin-right: 30px;
        padding-bottom: 5px;
        &:last-child {
          margin-right: 0;
        }
        &.active {
          color: $priceColor;
          font-weight: bold;
          border-bottom: 2px solid $priceColor;
        }
      }
    }
  }

  .goods-warn {
    background: $background;
    min-height: 600px;
    margin-top: $marginBase;
  }

  .number-box {
    display: flex;
    align-items: center;

    .label {
      width: 60px;
      color: #999;
      padding-left: 10px;
    }
  }

  .g-name {
    font-size: 22px;
  }

  .g-desc {
    color: #999;
    margin-top: 10px;
  }

  .g-price {
    margin-top: 10px;

    span {
      &::before {
        content: '¥';
        font-size: 14px;
      }

      &:first-child {
        color: $priceColor;
        margin-right: 10px;
        font-size: 22px;
      }
    }
  }

  .g-service {
    background: #f5f5f5;
    width: 500px;
    padding: 20px 10px 0 10px;
    margin-top: 10px;

    dl {
      padding-bottom: 20px;
      display: flex;
      align-items: center;

      dt {
        width: 50px;
        color: #999;
      }

      dd {
        color: #666;

        &:last-child {
          span {
            margin-right: 10px;

            &::before {
              content: '•';
              color: $xtxColor;
              margin-right: 2px;
            }
          }

          a {
            color: $xtxColor;
          }
        }
      }
    }
  }

  .xtx-numbox {
    display: flex;
    align-items: center;
    padding: 10px;

    .label {
      width: 30px;
      font-size: 14px;
      color: #666;
      margin-right: 10px;
    }

    .numbox {
      display: flex;
      align-items: center;

      a {
        display: block;
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        background-color: #f5f5f5;
        cursor: pointer;

        &:hover {
          background-color: #ebebeb;
        }
      }

      span {
        display: block;
        width: 30px;
        text-align: center;
        font-size: 14px;
        color: #666;
      }
    }
  }

  .btn {
    margin-top: $marginBase;
  }
}

.goods-tabs {
  nav {
    display: flex;
    height: 70px;
    line-height: 70px;
    border-bottom: 1px solid #f5f5f5;

    a {
      padding: 0 40px;
      font-size: 18px;
      position: relative;

      >span {
        color: $priceColor;
        font-size: 16px;
        margin-left: 10px;
      }
    }
  }
}

.goods-detail {
  display: grid;
  place-items: center;
  height: 100%;
}

</style>
